package logic

import (
	"context"
	"time"
	"xialou_platform/services/agent/model"

	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/agent/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentUserAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAgentUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AgentUserAddLogic {
	return &AgentUserAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 销氪绑定c端用户
func (l *AgentUserAddLogic) AgentUserAdd(in *agentClient.AgentUser) (*agentClient.EmptyBody, error) {
	agentUser, err := l.svcCtx.AgentUserModel.FindOneByUserId(l.ctx, in.UserId)
	if err != nil {
		if err == model.ErrNotFound {
			agentUser = &model.AgentUser{
				Id:         l.svcCtx.Flake.Generate().Int64(),
				AgentId:    in.AgentId,
				UserId:     in.UserId,
				CreateTime: time.Now(),
				Status:     in.Status,
				UpdateTime: time.Now(),
				SourceType: in.SourceType,
				SourceId:   in.SourceId,
			}
			_, err := l.svcCtx.AgentUserModel.Insert(l.ctx, agentUser)
			if err != nil {
				return nil, err
			}
			return &agentClient.EmptyBody{}, nil
		}
		return nil, err
	}

	return &agentClient.EmptyBody{}, nil
}
